﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Common.Logging;
using System.Reflection;
using MayfairFramework.Common.Resource;

namespace MayfairFramework.Common.Validation
{
    public sealed class Validator
    {
        /// <summary>
        /// 
        /// </summary>
        private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        /// <summary>
        /// コンストラクタ
        /// </summary>
        private Validator() { }

        /// <summary>
        /// Validate実行
        /// </summary>
        /// <typeparam name="TSelf">自身を定義する型</typeparam>
        /// <param name="self">自身</param>
        /// <returns>Messages</returns>
        public static Messages Validate<TSelf>(TSelf self)
        {
            Messages msgs = new Messages();
            Type type = self.GetType();
            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo property in properties)
            {
                object[] attributes = property.GetCustomAttributes(typeof(RequiredAttribute), false);
                foreach (RequiredAttribute attribute in attributes)
                {
                    if (attribute != null)
                    {
                        object target = property.GetGetMethod().Invoke(self, null);
                        if (target == null)
                        {
                            msgs.Add(attribute.Target, new Message("Null_Required", attribute.Target));
                        }
                        else if (target is string)
                        {
                            if (string.IsNullOrEmpty((string)target))
                            {
                                msgs.Add(attribute.Target, new Message("Null_Required", attribute.Target));
                            }
                        }
                    }
                }
            }
            return msgs;
        }
    }
}
